﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using BookClubPortal.Models;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using WebMatrix.WebData;
using System.Configuration;
using System.Web.Configuration;
using System.Net.Mail;
using System.Net.Configuration;

namespace BookClubPortal
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private List<Genre> GetGenreList()
        {
            return new List<Genre>
                {
                    new Genre { Name = "Action and Adventure" },
                    new Genre { Name = "Chick Lit" },
                    new Genre { Name = "Children’s" },
                    new Genre { Name = "Commercial Fiction" },
                    new Genre { Name = "Contemporary" },
                    new Genre { Name = "Crime" },
                    new Genre { Name = "Erotica" },
                    new Genre { Name = "Family Saga" },
                    new Genre { Name = "Fantasy" },
                    new Genre { Name = "Dark Fantasy" },
                    new Genre { Name = "Gay and Lesbian" },
                    new Genre { Name = "General Fiction" },
                    new Genre { Name = "Graphic Novels" },
                    new Genre { Name = "Historical Fiction" },
                    new Genre { Name = "Horror" },
                    new Genre { Name = "Humour" },
                    new Genre { Name = "Literary Fiction" },
                    new Genre { Name = "Military and Espionage" },
                    new Genre { Name = "Multicultural" },
                    new Genre { Name = "Mystery" },
                    new Genre { Name = "Offbeat or Quirky" },
                    new Genre { Name = "Picture Books" },
                    new Genre { Name = "Religious and Inspirational" },
                    new Genre { Name = "Romance" },
                    new Genre { Name = "Science Fiction" },
                    new Genre { Name = "Short Story Collections" },
                    new Genre { Name = "Thrillers and Suspense" },
                    new Genre { Name = "Western" },
                    new Genre { Name = "Women’s Fiction" },
                    new Genre { Name = "Young Adult" },
                    new Genre { Name = "Art & Photography" },
                    new Genre { Name = "Biography & Memoirs" },
                    new Genre { Name = "Business & Finance" },
                    new Genre { Name = "Celebrity & Pop Culture" },
                    new Genre { Name = "Music, Film & Entertainment" },
                    new Genre { Name = "Cookbooks" },
                    new Genre { Name = "Cultural/Social Issues" },
                    new Genre { Name = "Current Affairs & Politics" },
                    new Genre { Name = "Food & Lifestyle" },
                    new Genre { Name = "Gardening" },
                    new Genre { Name = "General Non-Fiction" },
                    new Genre { Name = "History & Military" },
                    new Genre { Name = "Home Decorating & Design" },
                    new Genre { Name = "How To" },
                    new Genre { Name = "Humour & Gift Books" },
                    new Genre { Name = "Journalism" },
                    new Genre { Name = "Juvenile" },
                    new Genre { Name = "Medical, Health & Fitness" },
                    new Genre { Name = "Narrative" },
                    new Genre { Name = "Nature & Ecology" },
                    new Genre { Name = "Parenting" },
                    new Genre { Name = "Pets" },
                    new Genre { Name = "Psychology" },
                    new Genre { Name = "Reference" },
                    new Genre { Name = "Relationship & Dating" },
                    new Genre { Name = "Religion & Spirituality" },
                    new Genre { Name = "Science & Technology" },
                    new Genre { Name = "Self-Help" },
                    new Genre { Name = "Sports" },
                    new Genre { Name = "Travel" },
                    new Genre { Name = "True Adventure & True Crime" },
                    new Genre { Name = "Women’s Issues" }
                };
        }

        private void InitializeNoDB()
        {
            Database.SetInitializer<BookClubPortalEntities>(null);

            try
            {
                using (var context = new BookClubPortalEntities())
                {
                    bool databaseExists = context.Database.Exists();

                    if (!databaseExists)
                    {
                        // Create the SimpleMembership database without Entity Framework migration schema
                        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    }

                    if (!WebSecurity.Initialized)
                    {
                        WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Users", "UserId", "UserName", autoCreateTables: true);
                    }

                    if (databaseExists)
                    {
                        return;
                    }

                    List<Genre> genres = GetGenreList();
                    genres.ForEach(a => context.Genres.Add(a));

                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
            }
        }

        public static void SendEmail(string to, string subject, string message)
        {
            if (to.Equals(string.Empty) || subject.Equals(string.Empty) || message.Equals(string.Empty))
            {
                return;
            }
            var mailMessage = new MailMessage();
            var smtpClient = new SmtpClient();

            mailMessage.To.Add(to);
            mailMessage.Subject = subject;
            mailMessage.Body = message;
            smtpClient.Send(mailMessage);
        }

        public static string GetApplicationEmailAddress()
        {
            try
            {
                SmtpSection smtpSettings = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
                return smtpSettings.From;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        /// example: catch application errors
//        protected void Application_Error(object sender, EventArgs e)
//        {
//            var context = HttpContext.Current;
//            var exception = context.Server.GetLastError();

//            if (exception is HttpRequestValidationException)
//            {
//                context.Server.ClearError();
//                Response.Clear();
//                Response.StatusCode = 200;

//                Response.Write(@"
//                    <html>
//                    <head><title>HTML Not Allowed</title></head>
//                    <body style='font-family: Arial, Sans-serif;'>
//                    <h1>Oops!</h1>
//                    <p>We are sorry, but HTML entry is not allowed on that page.</p>
//                    <p>Please make sure that your entries do not contain any angle brackets like &lt; or &gt;.</p>
//                    <p><a href='javascript:history.go(-1);'>Go back</a></p>
//                    </body>
//                    </html>");
//                Response.End();
//                return;
//            }
//        }

        protected void Application_Start()
        {
            InitializeNoDB();
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
    }
}